<?php

namespace App\Services;

use App\Models\OperationLog;
use Illuminate\Database\Eloquent\Builder;

class OperationLogService
{
    /**
     * 构建查询
     *
     * @param array $filters
     * @return Builder
     */
    public function buildQuery(array $filters = []): Builder
    {
        $query = OperationLog::with('user');

        if (!empty($filters['username'])) {
            $query->where('username', 'like', '%' . $filters['username'] . '%');
        }

        if (!empty($filters['path'])) {
            $query->where('path', 'like', '%' . $filters['path'] . '%');
        }

        if (isset($filters['status']) && $filters['status'] !== '') {
            $query->where('status', $filters['status']);
        }

        // 新增：按操作类型过滤
        if (!empty($filters['action'])) {
            $query->where('action', $filters['action']);
        }

        // 新增：按资源类型过滤
        if (!empty($filters['resource'])) {
            $query->where('resource', $filters['resource']);
        }

        // 新增：按资源ID过滤
        if (!empty($filters['resource_id'])) {
            $query->where('resource_id', $filters['resource_id']);
        }

        // 新增：按操作描述搜索
        if (!empty($filters['description'])) {
            $query->where('description', 'like', '%' . $filters['description'] . '%');
        }

        if (!empty($filters['start_time'])) {
            $query->where('created_at', '>=', $filters['start_time']);
        }

        if (!empty($filters['end_time'])) {
            $query->where('created_at', '<=', $filters['end_time']);
        }

        return $query->orderBy('id', 'desc');
    }

    /**
     * 清空所有日志
     *
     * @return bool
     */
    public function clearAll(): bool
    {
        try {
            OperationLog::truncate();
            return true;
        } catch (\Exception $e) {
            \Log::error('清空操作日志失败: ' . $e->getMessage());
            return false;
        }
    }
}

